//
//  JWUpLoadImageViewController.m
//  见闻新闻
//
//  Created by brother on 16/3/15.
//  Copyright © 2016年 JoanBoat. All rights reserved.
//

#import "JWUpLoadImageViewController.h"

#import <MBProgressHUD.h>

#import "JWUserModel.h"

#import "JWUpUserDataTools.h"

@interface JWUpLoadImageViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;



@end

@implementation JWUpLoadImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self takePictureClick:nil];
    
   
    // Do any additional setup after loading the view from its nib.
}


-(void)takePictureClick:(UIButton *)sender {
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"图片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
                                  
    [actionSheet showInView:self.view];
    

}


#pragma mark UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {


    UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
    ipc.delegate =self;
    
    switch (buttonIndex){//拍照
        case 0:{
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [self.view.window addSubview:hud];
                hud.dimBackground = YES;
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"亲，色相头不翼而飞";
                hud.removeFromSuperViewOnHide = YES;
                [hud hide:YES afterDelay:3.0f];
                return;
            }else {
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:ipc animated:YES completion:nil];
            }
            break;
    }
    
        case 1:{//相册
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [self.view.window addSubview:hud];
                hud.dimBackground = YES;
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"亲，相册丢了";
                hud.removeFromSuperViewOnHide = YES;
                [hud hide:YES afterDelay:3.0f];
                return;
            }else{
                
            ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:ipc animated:YES completion:nil];
            ipc.allowsEditing = YES;
            }
            break;
    }
        default:
            break;
    }

}


#pragma mark - UIImagePickerControllerDelegate
/**
 *  在选择完成后调用
 *
 *
 *  info 包含图片信息
 */
 
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

    //销毁控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //获得图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    //显示图片
    self.imageView.image = image;
    
    
}





-(void)upLoadImage {

    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    
    NSString *urlPath = @"http://1.zhixinnews.applinzi.com/Home/User/upload";
    
    NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
    
    NSDictionary *tempDic = [UserDefaults objectForKey:UserInfo];
    
    JWUserModel *userModel = [JWUserModel mj_objectWithKeyValues:tempDic];
    
    NSDictionary *parameters = @{@"user_id":userModel.user_id};
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在上传";
    
    hud.dimBackground = YES;

    
    hud.mode =  MBProgressHUDModeAnnularDeterminate;
    [manger POST:urlPath parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSData *data = UIImageJPEGRepresentation(self.imageView.image, 1.0);
        
        NSData *data = UIImagePNGRepresentation(self.imageView.image);
        
        
        [formData appendPartWithFileData:data name:@"user_image" fileName:@"aaa.png" mimeType:@"image/png"];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"%f",uploadProgress.fractionCompleted);
        
        hud.progress = uploadProgress.fractionCompleted;
        
        hud.detailsLabelText = [NSString stringWithFormat:@"%.2f%%", uploadProgress.fractionCompleted*100];
        
        hud.detailsLabelColor = [UIColor whiteColor];
        
        hud.detailsLabelFont = [UIFont fontWithName:@"TimesNewRomanPSMT" size:18];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        
        hud.hidden = YES;
        
        [JWUpUserDataTools updataToModel];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        hud.hidden = YES;
        
        NSLog(@"error %@",error);
    }];
}






- (IBAction)UpLoadCilck:(id)sender {
    
    [self upLoadImage];
    
    
}









- (IBAction)back:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
